#!/usr/bin/python
# -*- coding:utf-8 -*-
#@author: rui.xu <mrxurui@gmail.com>
#Filename:
import web
import models
from datetime import datetime, timedelta
from google.appengine.ext import db

render = web.template.render('templates/')
## fenye
perpage = 10

urls = (
		'/','index',
		'/guestbook/?','guestbook',
		)


def _cntime():
	return datetime.utcnow() + timedelta(hours=+8)
class index:
	def GET(self):
		input=web.input(page=1)
		page=web.intget(input.page,1)
		comments = db.GqlQuery("SELECT * FROM Testdb ORDER BY date DESC")
		commcount =comments.count()
		page = int(page)
		offset = (page-1)*perpage
		pages = commcount/perpage
		if commcount <= perpage:
			comments = comments
		if commcount > perpage:
			comments = comments.fetch(offset=offset,limit=perpage)
		if commcount%perpage>0:
			pages = commcount/perpage + 1
		elif commcount%perpage ==0:
			pages = commcount/perpage
		else:
			pages = 1
		return render.index(comments = comments,commcount=commcount,pages=pages)

class guestbook:
	def POST(self):
		i = web.input()
		p = models.Testdb()
		p.author = i.author
		#p.content = i.content.replace('\r\n', '<br/>')
		p.content = i.content
		p.date = _cntime()
		p.put()
		return web.seeother('/')


app = web.application(urls, globals())
main = app.cgirun()
